package com.ubing.boot.notesforjava.test.juc;

import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName : readWriteLock
 * @Description : readWriteLock
 * @Author : Xxxxx
 * @Date: 2023-03-13 11:06
 */
public class readWriteLock {
        static Lock lock = new ReentrantLock();
        static Integer value=100;
        static ReadWriteLock rwLock=new ReentrantReadWriteLock();
        static Lock readLock = rwLock.readLock();
        static Lock writeLock = rwLock.writeLock();

        public static void  read(Lock lock){
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read  over"+value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
        public static void  write(Lock lock,Integer v){
        try {
            lock.lock();
            Thread.sleep(1000);
            value=v;
            System.out.println("write  over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        for(int i =0;i<18;i++){
            if(i==5||i==15){
                new Thread(()->write(writeLock,new Random().nextInt())).start();
            }
            new Thread(()->read(readLock)).start();
        }
    }

}
